package com.teamwhole.modules.sys.security;

import java.io.Serializable;
import java.util.List;

import javax.annotation.PostConstruct;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.teamwhole.common.utils.Encodes;
import com.teamwhole.common.utils.SpringContextHolder;
import com.teamwhole.common.utils.StringUtils;
import com.teamwhole.modules.sys.entity.Menu;
import com.teamwhole.modules.sys.entity.Role;
import com.teamwhole.modules.sys.entity.User;
import com.teamwhole.modules.sys.service.SystemService;
import com.teamwhole.modules.sys.service.UserService;
import com.teamwhole.modules.sys.utils.UserUtils;

public class SystemAuthorizingRealm extends AuthorizingRealm {
    
    private Logger logger = LoggerFactory.getLogger(getClass());
    
    private SystemService systemService;
    
    @Autowired
    private UserService userService;
    
    /**认证回调函数, 登录时调用**/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        int activeSessionSize = getSystemService().getSessionDao().getActiveSessions(false).size();
        if (logger.isDebugEnabled()) {
            logger.debug("login submit, active session size: {}, username: {}", activeSessionSize, token.getPrincipal().toString());
        }
        // 校验用户名密码
        User user = userService.findByLoginName(token.getPrincipal().toString());
        if (user != null) {
            byte[] salt = Encodes.decodeHex(user.getPassword().substring(0, 16));
            return new SimpleAuthenticationInfo(new Principal(user), user.getPassword().substring(16), ByteSource.Util.bytes(salt), getName());
        } else {
            return null;
        }
    }
    
    /**授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用**/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Principal principal = (Principal) getAvailablePrincipal(principals);
        User user = userService.findByLoginName(principal.getLoginName());
        if (user != null) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            List<Menu> list = UserUtils.getMenuList();
            for (Menu menu : list) {
                if (StringUtils.isNotBlank(menu.getPermission())) {
                    // 添加基于Permission的权限信息
                    for (String permission : StringUtils.split(menu.getPermission(), ",")) {
                        info.addStringPermission(permission);
                    }
                }
            }
            // 添加用户权限
            info.addStringPermission("user");
            // 添加用户角色信息
            for (Role role : user.getRoleList()) {
                info.addRole(role.getId());
            }
            // 更新登录IP和时间
            //getSystemService().updateUserLoginInfo(user);
            // 记录登录日志
            //LogUtils.saveLog(Servlets.getRequest(), "系统登录");
            return info;
        }
        return null;
    }
    
    /**设定密码校验的Hash算法与迭代次数 **/
    @PostConstruct
    public void initCredentialsMatcher() {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(SystemService.HASH_ALGORITHM);
        matcher.setHashIterations(SystemService.HASH_INTERATIONS);
        setCredentialsMatcher(matcher);
    }
    
    /**获取业务对象**/
    public SystemService getSystemService() {
        if (systemService == null) {
            systemService = SpringContextHolder.getBean(SystemService.class);
        }
        return systemService;
    }
    
    /**授权用户信息**/
    public static class Principal implements Serializable {
        private static final long serialVersionUID = 1L;
        private String id;          // 编号
        private String loginName;   // 登录名
        private String name;        // 姓名
        
        public Principal(User user) {
            this.id = user.getId();
            this.loginName = user.getLoginName();
            this.name = user.getName();
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getLoginName() {
            return loginName;
        }

        public void setLoginName(String loginName) {
            this.loginName = loginName;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
        
        /**获取SESSIONID**/
        public String getSessionid() {
            try{
                return (String) UserUtils.getSession().getId();
            }catch (Exception e) {
                return "";
            }
        }
        
        @Override
        public String toString() {
            return id;
        }
    }
    
    public void clearCache() {
        PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
        super.clearCache(principals);
    }

}